package com.example.administrator.im.ui.activity;

import android.Manifest;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.transition.Slide;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.transition.TransitionSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;
import com.example.administrator.im.adapter.DetailsAdapter;
import com.example.administrator.im.config.ImageConfig;
import com.example.administrator.im.config.PhoneParam;
import com.example.administrator.im.data.DetailsData;
import com.example.administrator.im.db.UserDBHelper;
import com.example.administrator.im.interfacz.Detailsable;
import com.example.administrator.im.interfacz.ShareTitleable;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.utils.DialogUtils;
import com.example.administrator.im.utils.DownloadImageUtils;
import com.example.administrator.im.utils.EMUtils;
import com.example.administrator.im.utils.FileUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.example.administrator.im.view.ShareTitle;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * create:2018/10/2 16:15
 * author: 姚鸿杰
 **/
public class PersonalActivity extends AppCompatActivity {

    private final String TAG = "PersonalActivity";

    private ShareTitle shareTitle;

    private ImageView head_img;

    private TextView tv_nickname;

    private String username;

    private RecyclerView recycler_personal;
    private DetailsAdapter adapter;


    public static final String TITLE[] = {"账号", "昵称", "个性签名", "邮箱", "性别"};

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            String content = msg.obj.toString();
            switch (msg.what) {
                case UPDATE_IMAGES:
                    setHead_img(null);
                    break;
                case UPDATE_NICKNAME:
                    tv_nickname.setText(content);
                case UPDATE_SIGNATURE:
                case UPDATE_EMAIL:
                case UPDATE_SEX:
                    adapter.updateItem(content, msg.arg1);
                    break;
            }
        }
    };
    private final int ALBUM = 1;
    private final int TAKE_PHOTO = 2;

    private final int UPDATE_IMAGES = 1;
    private final int UPDATE_NICKNAME = 2;
    private final int UPDATE_SIGNATURE = 3;
    private final int UPDATE_EMAIL = 4;
    private final int UPDATE_SEX = 5;

    private String headPath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Transition transition = TransitionInflater.from(this).inflateTransition(R.transition.share_enter);
        getWindow().setEnterTransition(transition);

        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT);

        setContentView(R.layout.activity_personal);

        Intent intent = getIntent();
        if (intent != null) {
            headPath = intent.getStringExtra("headImg");
        }

        initView();
        initDate();
    }

    private void initView() {

        shareTitle = (ShareTitle) findViewById(R.id.personal_toolbar);
        shareTitle.setIconOnClickListener(new ShareTitleable() {
            @Override
            public void left_click(View v) {
                finish();
            }

            @Override
            public void right_click(View v) {
                updateImgAlert();
            }
        });

//        ivReveal.post(new Runnable() {
//            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//            @Override
//            public void run() {
//                //隐藏
////                Animator animation = ViewAnimationUtils.createCircularReveal(ivReveal,     ivReveal.getWidth() / 2,
////                        ivReveal.getHeight() / 2, ivReveal.getWidth() / 2, 0);
////                animation.setInterpolator(new AccelerateDecelerateInterpolator());
////                animation.setDuration(1500).start();
////                animation.addListener(new AnimatorListenerAdapter() {
////                    @Override
////                    public void onAnimationEnd(Animator animation) {
////                        super.onAnimationEnd(animation);
////                        ivReveal.setVisibility(View.INVISIBLE);
////                    }
////                });
//
//                //显示
//
//                Animator animation = ViewAnimationUtils.createCircularReveal(ivReveal, ivReveal.getWidth() / 2,
//                        ivReveal.getHeight() / 2, ShareConfig.getInstance().getImg_height(), Math.max(ivReveal.getHeight(), ivReveal.getWidth()));
//                animation.setInterpolator(new AccelerateInterpolator());
//                animation.setDuration(800).start();
//            }
//        });

        tv_nickname = (TextView) findViewById(R.id.nickname);

        head_img = (ImageView) findViewById(R.id.rl);
        //head_img.setImageBitmap(BitmapFactory.decodeFile(headPath));

        recycler_personal = (RecyclerView) findViewById(R.id.recycler_personal);
//        recycler_personal.post(new Runnable() {
//            @Override
//            public void run() {
//                TranslateAnimation ta = new TranslateAnimation(0, 0,
//                        PhoneParam.getInstance(PersonalActivity.this).getActivity_height(), 0);
//                ta.setDuration(800);
//                recycler_personal.startAnimation(ta);
//            }
//        });
    }


    private void initDate() {
        SharedPreferences spf = getSharedPreferences("user", Context.MODE_PRIVATE);
        username = spf.getString("username", "");

        UserDBHelper user = LitePal.where("username = ?",
                username).findFirst(UserDBHelper.class);
        if (user == null)
            return;
        tv_nickname.setText(user.getNickname());
        List<DetailsData> list = new ArrayList<>();
        list.add(new DetailsData(TITLE[0], username, false));
        list.add(new DetailsData(TITLE[1], user.getNickname(), false));
        list.add(new DetailsData(TITLE[2], user.getSignature(), false));
        list.add(new DetailsData(TITLE[3], TextUtils.isEmpty(user.getEmail()) ? "未填写" : user.getEmail(), true));
        list.add(new DetailsData(TITLE[4], user.getSex(), false));

        recycler_personal.setLayoutManager(new LinearLayoutManager(this));
        adapter = new DetailsAdapter(list, this);
        recycler_personal.addItemDecoration(new
                com.example.administrator.im.adapter.DividerItemDecoration(this, LinearLayout.VERTICAL));
        recycler_personal.setAdapter(adapter);

        adapter.setOnClickListener(new Detailsable() {
            @Override
            public void onClick(View v, int position) {
                switch (position) {
                    case 1:
                        updateNickname(position);
                        break;
                    case 2:
                        updateSignature(position);
                        break;
                    case 3:
                        updateEmail(position);
                        break;
                    case 4:
                        updateSex(position);
                        break;
                }
            }
        });

//        String url = HttpUtils.PORT + user.getImg_path();
//        if (TextUtils.equals(url, HttpUtils.PORT)) {
//            return;
//        }

        setHead_img(null);
    }


    private void setHead_img(Bitmap bitmap) {
        Bitmap mbitmap = null;
        if (bitmap == null)
            mbitmap = BitmapFactory.decodeFile(headPath);
        else {
            mbitmap = bitmap;
        }
        RequestOptions options = new RequestOptions().placeholder(R.color.theme_color).diskCacheStrategy(DiskCacheStrategy.NONE)
                .error(R.color.theme_color).override(ImageConfig.getPersonalBig(), ImageConfig.getPersonalBig());
        Glide.with(this).load(mbitmap).apply(options).into(head_img);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private EditText et_content;
    private Button dialog_yes;

    private View getDialogLayout(String title, String hint, int minLines) {
        LayoutInflater inflater = this.getLayoutInflater();
        View view_custom = inflater.inflate(R.layout.dialog_add_group, null, false);
        TextView tv_title = view_custom.findViewById(R.id.dialog_tv_title);

        et_content = view_custom.findViewById(R.id.dialog_et_name);
        et_content.setHint(hint);
        et_content.setMaxLines(minLines);
        et_content.setFilters(new InputFilter[]{new InputFilter.LengthFilter(minLines == 1 ? 20 : 45)}); //最大输入长度

        tv_title.setText(title);
        dialog_yes = (Button) view_custom.findViewById(R.id.dialog_yes);
        return view_custom;
    }

    private AlertDialog getAlertDialog(String title, String hint, int minLines) {
        View v = getDialogLayout(title, hint, minLines);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setView(v);
        final AlertDialog alert = builder.create();
        alert.show();

        v.findViewById(R.id.dialog_no).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });
        return alert;
    }

    private void openLoading() {
        DialogUtils.setDialog(PersonalActivity.this, R.layout.loading);
        DialogUtils.showDialog();
    }

    private void updateNickname(final int position) {
        final AlertDialog alert_nickname = getAlertDialog("昵称", "请输入昵称", 1);
        dialog_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert_nickname.dismiss();
                final String nickname = et_content.getText().toString();
                if (TextUtils.isEmpty(nickname)) {
                    Toast.makeText(PersonalActivity.this, "昵称不能为空!!!", Toast.LENGTH_SHORT).show();
                    return;
                }

                openLoading();
                HttpUtils.updateUserRequest(HttpUtils.UPDATE_NICKNAME, nickname, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, e.getMessage());
                        DialogUtils.clearAlerDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        DialogUtils.clearAlerDialog();
                        String content = response.body().string();
                        Log.e(TAG, content);
                        Gson gson = new Gson();
                        final ResultJson json = gson.fromJson(content, ResultJson.class);
                        if (json.getCode() == HttpUtils.SUCCESS) {

                            //修改本地数据库
                            UserDBHelper user = LitePal.where("username = ?", username).findFirst(UserDBHelper.class);
                            user.setNickname(nickname);
                            user.save();

                            //更新UI
                            handler.sendMessage(getMessage(UPDATE_NICKNAME, nickname, position));

                            EMUtils.sendAlphaMessage(EMUtils.UPDATE_NICKNAME);

                        } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                            Log.e(TAG, json.getData().toString());
                        }
                    }
                });
            }
        });
    }

    private void updateSignature(final int position) {
        final AlertDialog alert_signature = getAlertDialog("个性签名", "请输入个性签名", 3);
        dialog_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert_signature.dismiss();

                final String signature = et_content.getText().toString();
                openLoading();
                HttpUtils.updateUserRequest(HttpUtils.UPDATE_SIGNATURE, signature, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, e.getMessage());
                        DialogUtils.clearAlerDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        DialogUtils.clearAlerDialog();
                        String content = response.body().string();
                        Gson gson = new Gson();
                        final ResultJson json = gson.fromJson(content, ResultJson.class);
                        if (json.getCode() == HttpUtils.SUCCESS) {

                            UserDBHelper user = LitePal.where("username = ?", username).findFirst(UserDBHelper.class);
                            user.setSignature(signature);
                            user.save();

                            handler.sendMessage(getMessage(UPDATE_SIGNATURE, signature, position));

                            EMUtils.sendAlphaMessage(EMUtils.UPDATE_SIGNATURE);

                        } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                            Log.e(TAG, json.getData().toString());
                        }
                    }
                });
            }
        });
    }

    private void updateEmail(final int position) {
        final AlertDialog alert_email = getAlertDialog("邮箱", "请输入邮箱", 1);
        dialog_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert_email.dismiss();

                final String email = et_content.getText().toString();
                openLoading();
                HttpUtils.updateUserRequest(HttpUtils.UPDATE_EMAIL, email, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, e.getMessage());
                        DialogUtils.clearAlerDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        DialogUtils.clearAlerDialog();
                        String content = response.body().string();
                        Log.e(TAG, content);
                        Gson gson = new Gson();
                        final ResultJson json = gson.fromJson(content, ResultJson.class);
                        if (json.getCode() == HttpUtils.SUCCESS) {

                            UserDBHelper user = LitePal.where("username = ?", username).findFirst(UserDBHelper.class);
                            user.setEmail(email);
                            user.save();

                            handler.sendMessage(getMessage(UPDATE_EMAIL, email, position));

                        } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                            Log.e(TAG, json.getData().toString());
                        }
                    }
                });
            }
        });
    }

    private void updateSex(final int position) {
        final String[] items = {"男", "女"};
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String sex = LitePal.where("username = ?", username).findFirst(UserDBHelper.class).getSex();
        int count = 0;
        for (int i = 0; i < items.length; i++)
            if (items[i].equals(sex)) {
                count = i;
                break;
            }

        final int flag = count;
        // 设置参数
        builder.setIcon(R.mipmap.grounp).setTitle("选择性别").setSingleChoiceItems(items, flag
                , new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {

                        dialog.dismiss();
                        if (which == flag) return;

                        openLoading();
                        HttpUtils.updateUserRequest(HttpUtils.UPDATE_SEX, items[which], new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Log.e(TAG, e.getMessage());
                                DialogUtils.clearAlerDialog();
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                DialogUtils.clearAlerDialog();
                                String content = response.body().string();
                                Gson gson = new Gson();
                                final ResultJson json = gson.fromJson(content, ResultJson.class);
                                if (json.getCode() == HttpUtils.SUCCESS) {

                                    UserDBHelper user = LitePal.where("username = ?", username).findFirst(UserDBHelper.class);
                                    user.setSex(items[which]);
                                    user.save();

                                    handler.sendMessage(getMessage(UPDATE_SEX, items[which], position));

                                } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                                    Log.e(TAG, json.getData().toString());
                                }
                            }
                        });
                    }
                });
        builder.create().show();
    }

    private AlertDialog dialog;

    private void updateImgAlert() {
        LayoutInflater inflater = this.getLayoutInflater();
        View view = inflater.inflate(R.layout.update_img, null, false);
        Button shooting = (Button) view.findViewById(R.id.shooting);
        Button album = (Button) view.findViewById(R.id.album);

        final AlertDialog.Builder listDialog = new AlertDialog.Builder(this);
        listDialog.setView(view);
        dialog = listDialog.create();
        dialog.show();
        shooting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = FileUtils.getFilePath(username, FileUtils.USER_PACK);
                try {
                    if (file.exists()) {
                        file.delete();
                    }
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    imageUri = FileProvider.getUriForFile(PersonalActivity.this,
                            "com.example.administrator.im.fileprovider", file);
                } else {
                    imageUri = Uri.fromFile(file);
                }

                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, TAKE_PHOTO);
            }
        });
        album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //申请权限
                if (ContextCompat.checkSelfPermission(PersonalActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(PersonalActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }
                dialog.dismiss();
            }
        });
    }

    private Uri imageUri;

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, ALBUM);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ALBUM) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openAlbum();
            } else {
                Toast.makeText(this, "权限不够请到设置里设置", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ALBUM) {
            if (resultCode == RESULT_OK) {
                handleImageOnKitKat(data);
            }
        } else if (requestCode == TAKE_PHOTO) {
            if (resultCode == RESULT_OK) {
                sendMultipart(headPath);
            }
        }
    }

    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        sendMultipart(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void sendMultipart(final String imagePath) {

        HttpUtils.UploadImagesRequest(imagePath, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String content = response.body().string();
                Gson gson = new Gson();
                final ResultJson json = gson.fromJson(content, ResultJson.class);
                if (json.getCode() == HttpUtils.SUCCESS) {
                    UserDBHelper user = LitePal.where("username = ?", username).findFirst(UserDBHelper.class);
                    user.setImg_path(json.getData().toString());
                    user.save();

                    //handler.sendMessage(getMessage(UPDATE_IMAGES, HttpUtils.PORT + json.getData().toString(), -1));
                    File file = FileUtils.getFilePath(username, FileUtils.USER_PACK);
                    saveImage(HttpUtils.PORT + json.getData().toString(), file, ImageConfig.getPersonalBig());

                    EMUtils.sendAlphaMessage(EMUtils.UPDATE_IMAGE);
                } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                }
            }
        });
    }

    private void saveImage(String url, final File file, int size) {
        DownloadImageUtils downloadImage = new DownloadImageUtils(url, MyApplication.getmContext(),
                size, size, file, new DownloadImageUtils.ImagedownLoadCallBack() {
            @Override
            public void onDownLoadSuccess(final File file) {
                headPath = file.getPath();
                setHead_img(null);
            }

            @Override
            public void onDownLoadFailed() {
            }
        });
        new Thread(downloadImage).start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(dialog != null){
            dialog.dismiss();
        }
    }

    private Message getMessage(int what, String content, int arg) {
        Message msg = new Message();
        msg.what = what;
        msg.obj = content;
        msg.arg1 = arg;
        return msg;
    }

}
